package com.wn34.goods.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wn34.goods.entity.Goods;
import com.wn34.goods.entity.Order;
import com.wn34.goods.mapper.GoodsMapper;
import com.wn34.goods.mapper.OrderMapper;
import com.wn34.goods.service.OrderService;
import com.wn34.goods.vo.OrdersVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    OrderMapper orderMapper;

    @Autowired
    GoodsMapper goodsMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int saveOrders(Integer userid, Integer gid, Integer gnum) {
        Order order = orderMapper.selectExist(userid, gid);
        if (order == null) {
            order = new Order();
            order.setOrdernum(gnum);
            order.setCreatedate(new Date());
            order.setGoodsId(gid);
            order.setUserId(userid);
            order.setStatus(1);
            orderMapper.insert(order);
        } else {
            order.setOrdernum(order.getOrdernum() + gnum);
            orderMapper.updateByPrimaryKey(order);
        }
        Goods goods = goodsMapper.selectByPrimaryKey(gid);
        goods.setCount(goods.getCount() - gnum);
        goodsMapper.updateByPrimaryKey(goods);
        return 1;
    }

    @Override
    public PageInfo<OrdersVo> pageInfo(Integer now, Integer size, Integer userid) {
        PageHelper.startPage(now, size);
        List<OrdersVo> list = orderMapper.selectByUserId(userid);
        return new PageInfo<OrdersVo>(list);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer removeOrder(Integer orderId) {
        Order order = orderMapper.selectByPrimaryKey(orderId);
        Goods goods = goodsMapper.selectByPrimaryKey(order.getGoodsId());
        goods.setCount(order.getOrdernum() + goods.getCount());
        goodsMapper.updateByPrimaryKey(goods);
        orderMapper.deleteByPrimaryKey(orderId);
        return 1;
    }
}
